package game.phases.actionphase 
{
	import game.unitmanager.ArmyController;
	import game.unitmanager.OrderTypes;
	/**
	 * ...
	 * @author rnk
	 */
	public class RaidSolver extends Solver
	{
		private var raidingArmies:Array;
		private var currentArmyIdx:int;
		
		public function RaidSolver() 
		{
			
		}
		
		override public function Enter():void 
		{
			//prepare
			papa.papa.mapView.SetArmiesMouseListeners(false);
			papa.papa.mapView.LockArmies(true, 0, true);
			
			//get raiding armies list
			var allArmies:Array = papa.papa.unitsManager.GetArmies();
			raidingArmies = [];
			for each (var armyController:ArmyController in allArmies) 
			{
				if (armyController.order == OrderTypes.RAID && armyController.loyalty != 0 )
				{
					raidingArmies.push(armyController);
				}
			}
			
			//sort by initiative
			raidingArmies.sort(
				function(armyA:ArmyController, armyB:ArmyController):Number
				{
					var priceA:Number = armyA.GetInitiative();
					var priceB:Number = armyB.GetInitiative();
					
					if (priceA > priceB) return 1;
					if (priceA < priceB) return -1;
					return 0;
				}
			);
			
			//if no armies then skip solver
			if (raidingArmies.length == 0)
			{
				Finish();
				return;
			}
			
			//give it controls
			currentArmyIdx = 0;
			GiveControlToArmy(currentArmyIdx);
			
		}
		
		private function GiveControlToArmy(idx:int):void 
		{
			currentArmyIdx = idx;
			
			var army:ArmyController = raidingArmies[idx];
			
			//skip if army has no raid order
			if (army.order != OrderTypes.RAID)
			{
				OnArmyFinishedRaiding();
				return;
			}
			
			//show player name
			papa.papa.gui.SetCurrentPlayer(papa.papa.GetPlayer(army.loyalty));
			
			//start raid command in army controller give him callback
			papa.papa.mapView.SelectProvinceToRaid(army.model.province.uid, OnRaidTargetSelected);
			
		}
		
		private function OnRaidTargetSelected(provinceUid:String):void
		{
			(raidingArmies[currentArmyIdx] as ArmyController).SetOrder( -1);
			
			//if cancel
			if (provinceUid == (raidingArmies[currentArmyIdx] as ArmyController).model.province.uid)
			{
				OnArmyFinishedRaiding();
				return;
			}
			
			//get army in that province
			var armyController:ArmyController = papa.papa.unitsManager.GetArmy(provinceUid);
			armyController.SetOrder( -1);
			
			
			OnArmyFinishedRaiding();
			
		}
		
		private function OnArmyFinishedRaiding():void
		{
			papa.papa.gui.SetCurrentPlayer(null);
			
			
			currentArmyIdx++;
			if (currentArmyIdx < raidingArmies.length)
			{
				GiveControlToArmy(currentArmyIdx);
			} else
			{
				Finish();
			}
		}
		
		override public function Exit():void 
		{
			
			
			
		}
		
		
	}

}